﻿const logger = require('./logs/logger');

let rules = [];

module.exports = {
    fake(req) {
        rules.forEach((v, i, s) => {
            if (v.enable && v.isMatch(req, null)) {
                try {
                    if (v.fake) {
                        logger.debug(`fake url -> ${req.url}`)
                        v.fake(req);
                    }
                } catch (e) {
                    logger.debug(`rule -> ${v.name}, error -> ${e}, stack -> ${e.stack}`);
                }
            }
        });
    },

    async execute(req, resp) {
        for (let i = 0; i < rules.length; i++ ) {
            let v = rules[i];
            if (v.enable && v.isMatch(req, resp)) {
                try {
                    await v.execute(req, resp);
                } catch (e) {
                    logger.debug(`rule -> ${v.name}, error -> ${e}, stack -> ${e.stack}`);
                }
            }
        }
    },

    use(rule) {
        if (rules.every((v, i, s) => v.name !== rule.name)) {
            rules.push(rule);
        }
    }
};